package servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.BaseDAO;

@SuppressWarnings("serial")
public class AppServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String action = request.getParameter("action");
		initHeader(response);
		if (action.equals("list")) {// 获取属面板列表
			renderText(this.getTreePanelList(), response);
		} else if (action.equals("node")) {
			renderText(this.getTreeNodeList(request.getParameter("id")),
					response);
		}
	}
	
	public String getTreePanelList() {
		String sql = "select  t.id, t.text, t.component, "
				+ " t.description, t.type, t.iconCls, t.sort "
				+ " from resource t where t.parent_id is null";
		return BaseDAO.findBySql(sql).toString();
	}

	public String getTreeNodeList(String id) {
		String sql = "select  t.id, t.text, t.component, "
				+ " t.description, t.type, t.iconCls, t.sort,t.leaf "
				+ " from resource t where t.parent_id = '" + id + "'";
		return BaseDAO.findBySql(sql).toString();
	}

	public static void renderText(final String content,
			HttpServletResponse response) {
		try {
			response = initHeader(response);
			response.getWriter().write(content);
			response.getWriter().close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static HttpServletResponse initHeader(HttpServletResponse response) {
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		response.setCharacterEncoding("UTF-8");
		return response;
	}

	public static void main(String[] args) {
		String sql = "select  t.id, t.name, t.component, "
				+ " t.description, t.type, t.icon, t.sort "
				+ " from resource t where t.parent_id is null";
		System.out.println(BaseDAO.findBySql(sql));
	}
}
